// pages/addRentCar/addRentCar.js
let app = getApp()
let request = require('../../utils/request.js')
let util = require("../../utils/util")

Page({
  /**
   * 页面的初始数据
   */
  data: {
    pageAllHeight: app.globalData.pageAllHeight,
    moneyInput: '',
    telInput: '',
    inputLen: 8,
    activeIptIndex: -1,
    carNo: '',
    isFocus: true,
    calendarConfig: {
      // multi: true, // 是否开启多选,
      theme: 'elegant', // 日历主题，目前共两款可选择，默认 default 及 elegant，自定义主题在 theme 文件夹扩展
      markToday: '今', // 当天日期展示不使用默认数字，用特殊文字标记
      highlightToday: true, // 是否高亮显示当天，区别于选中样式（初始化时当天高亮并不代表已选中当天）
      inverse: true, // 单选模式下是否支持取消选中
    },
    nowDate: '',
    startDate: '',
    endDate: '',
    dateArr: [],
    monthType: [],
    monthList: [],
    monthIndex: 0,
    username: null
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let nowDate = util.formatTime(new Date())
    this.setData({
      nowDate: nowDate.year + '-' + nowDate.month + '-' + nowDate.day
    })
  },
  onReady() {
    this.getMonthType()
  },
  /**
   * 获取月租车类型
   */
  getMonthType() {
    let that = this
    let url = '/promotion/month-rule-fee-scale/getMonthRuleFeeScaleName'
    request.http(url, 'GET', { parkId: wx.getStorageSync('parkInfo').parkId })
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          let endDate = that.countDate(that.data.nowDate, data.data[that.data.monthIndex].days)
          let dateArr = [that.data.nowDate, endDate]
          that.setData({
            monthType: data.data,
            monthList: data.data,
            moneyInput: data.data[that.data.monthIndex].parkAmount,
            dateArr
          })
          // setTimeout(function () {
          //   that.calendar.chooseDateArea(dateArr);
          // }, 500)
        }
      })
  },
  bindPickerChange(e) {
    let endDate = this.countDate(this.data.nowDate, this.data.monthList[e.detail.value].days)
    let dateArr = [this.data.nowDate, endDate]
    this.setData({
      monthIndex: e.detail.value,
      moneyInput: this.data.monthList[e.detail.value].parkAmount,
      dateArr
    })
    this.calendar.chooseDateArea(dateArr);
  },
  /**
   * 收费金额
   */
  getMoney(e) {
    let value = e.detail.value
    this.setData({
      moneyInput: value
    })
  },
  /**
   * 车主姓名
   */
  getUsername(e){
    this.setData({ username: e.detail.value })
  },
  /**
   * 车主电话
   */
  getTel(e) {
    this.setData({ telInput: e.detail.value })
  },
  /**
   * 选择日期后执行的事件
   * currentSelect 当前点击的日期
   * allSelectedDays 选择的所有日期（当multi为true时，allSelectedDays有值）
   */
  afterTapDay(e) {
    let selectDate = e.detail
    selectDate = selectDate.year + '-' + selectDate.month + '-' + selectDate.day
    let dateArr = this.data.dateArr
    let today = this.data.nowDate
    if (today > selectDate) {
      wx.showToast({
        title: '开始时间不得小于当天时间',
        icon: 'none'
      })
      dateArr = []
      this.calendar.chooseDateArea([today]);
    } else {
      if (dateArr.length >= 2) {
        dateArr = []
      }
      dateArr.push(selectDate)
      this.calendar.chooseDateArea(dateArr);
      if (dateArr.length == 2) {
        if (dateArr[0] > dateArr[1]) {
          wx.showToast({
            title: '结束时间小于开始时间',
            icon: 'none'
          })
          dateArr = []
          dateArr.push(selectDate)
          this.calendar.chooseDateArea(dateArr);
        }
      }
    }
    console.log(dateArr);
    this.setData({
      dateArr
    })
  },
  /**
   * 输入车牌号
   * @param {*} e 
   */
  onFocus: function (e) {
    let inputType = 1;
    if (/^[\u4e00-\u9fa5]+/.test(this.data.carNo)) {
      inputType = 2;
    }
    this.setData({
      showPlateInput: true,
      inputType: inputType,
      activeIptIndex: this.data.carNo.length
    });
  },
  /**
   * 键盘输入操作
   * @param {*} e 
   */
  handlePlateChange(e) {
    let value = e.detail.value;
    let inputLen = this.data.inputLen;
    let type = e.detail.type;
    let carNo = this.data.carNo;
    if (carNo.length < inputLen) {
      carNo += value;
    }
    if (type == 1) {
      this.setData({
        inputType: 2
      })
    }
    this.setData({
      carNo,
      activeIptIndex: carNo.length
    })
  },
  /**
   * 点击键盘上的确定
   */
  handlePlateConfirm() {
    /* isCarPlate用于判断输入的车牌号是否符合规范 */
    if (!this.isCarPlate(this.data.carNo)) {
      wx.showToast({
        title: '请输入正确车牌号',
        icon: 'none'
      })
      return false;
    }
    this.setData({
      translateSpace: 0,
      showPlateInput: false,
      inputType: 1,
      activeIptIndex: -1
    })
  },
  /**
   * 用于键盘输入删除
   * @param {*} e 
   */
  handlePlateDelete(e) {
    let carNo = this.data.carNo;
    carNo = carNo.substring(0, carNo.length - 1);
    if (carNo.length == 0) {
      this.setData({
        inputType: 1
      })
    }
    this.setData({
      carNo,
      activeIptIndex: carNo.length
    })
  },
  /**
   * 判断车牌号
   * @param {String} value 车牌号
   */
  isCarPlate(value) {
    return /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/.test(value);
  },
  /**
   * 添加月卡按钮
   */
  addMonth() {
    let money = this.data.moneyInput
    let tel = this.data.telInput
    let car = this.data.carNo
    let startDate = this.data.dateArr[0]
    let endDate = this.data.dateArr[1]
    let feeScaleId = this.data.monthType[this.data.monthIndex].id
    let monthRentName = this.data.monthType[this.data.monthIndex].monthRentName
    let monthRentTypeId = this.data.monthType[this.data.monthIndex].monthRentTypeId
    let monthRuleId = this.data.monthType[this.data.monthIndex].monthRuleId
    let monthRulePullId = this.data.monthType[this.data.monthIndex].monthRulePullId
    let parkId = wx.getStorageSync('parkInfo').parkId
    let parkSource = wx.getStorageSync('parkInfo').parkSource
    let moblieReg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/

    if (!moblieReg.test(tel)) {
      wx.showToast({ title: '请您填写正确手机号', icon: 'none' })
      return
    }
    if (!car) {
      wx.showToast({ title: '请您填写车牌号', icon: 'none' })
      return
    }
    if(this.data.username == null || this.data.username == ''){
      wx.showToast({ title: '请您填写车主姓名', icon: 'none' })
      return
    }
    let parmas = {
      beginTime: startDate + ' 00:00:00',
      carNumber: car,
      endTime: endDate + ' 23:59:59',
      feeScaleId,
      mobilePhone: tel,
      monthRentName,
      monthRentTypeId,
      monthRuleId,
      monthRulePullId,
      parkAmount: money,
      parkId: parkId,
      username: this.data.username
    }
    request.http(
      '/customer/card/add-park-month-car', 
      'POST', 
      parmas, 
      0
    ).then(res => {
      let data = res.data
      if (data.code == 200) {
        if (data.data.status == 1) {
          wx.showToast({ title: '添加成功' })
          wx.navigateBack({ delta: 1 })
        } else {
          wx.showToast({ title: data.data.message, icon: 'none' })
        }
      }
    })
  },
  /**
   * 计算日期
   * @param {*} date 初始日期  格式 yyyy-mm-dd
   * @param {*} time 增加天数
   */
  countDate(date, time) {
    var date = date
    var time = time
    let dateArr = date.split('-')
    let year = parseInt(dateArr[0])
    let month = parseInt(dateArr[1])
    let day = parseInt(dateArr[2])
    let newYear = year
    let newMonth = month
    let newDay = day
    if (month == 2) {
      if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
        console.log('您输入的年份是闰年'); //29
        newDay = day + time
        if (newDay > 29) {
          newDay = newDay - 29
          newMonth = month + 1
        }
      } else {
        console.log('您输入的年份是平年'); //28
        newDay = day + time
        if (newDay > 28) {
          newDay = newDay - 28
          newMonth = month + 1
        }
      }
    } else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
      newDay = day + time
      if (newDay > 31) {
        newDay = newDay - 31
        newMonth = month + 1
        if (newMonth > 12) {
          newMonth = 1
          newYear = year + 1
        }
      }
    } else {
      newDay = day + time
      if (newDay > 30) {
        newDay = newDay - 30
        newMonth = month + 1
      }
    }
    return newYear + '-' + (newMonth > 10 ? newMonth : '0' + newMonth) + '-' + (newDay > 10 ? newDay : '0' + newDay)
  },
  /**
   * 点击页面
   */
  clickPage(){
    this.setData({ showPlateInput: false })
  }
})